package com.yuan.springcloud.common.utils;

import com.yuan.springcloud.common.exception.ErrorEnum;
import com.yuan.springcloud.common.exception.ParamValidException;
import com.yuan.springcloud.common.exception.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Bean校验工具类
 * @author YouYuan
 * @date 2020/8/18 21:54
 */
public class ValidUtil {

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    private ValidUtil() {
    }

    public static void valid(Object object, Class<?>... groups) throws ServiceException {
        Set<ConstraintViolation<Object>> constraintViolations = VALIDATOR.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
//            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            /*直接抛出ParamValidException，供全局异常捕获，传递所有校验失败的数据信息用于组装错误消息提示*/
            throw new ParamValidException(ErrorEnum.PARAMS_VALID_ERR, constraintViolations);
        }
    }
}
